package com.idp.common.utils;

import java.util.Date;

import com.alibaba.fastjson.JSONObject;
import com.idp.common.constants.SystemParam;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;

public class WechatUtil {

	private static String ACCESS_TOKEN;
	private static long EXPIRES_TIME;

	private static String getToken() {

		Date now = new Date();

		if(StrUtil.isEmpty(ACCESS_TOKEN) || now.getTime() >= EXPIRES_TIME) {

			SystemParam params = ContextUtil.getBean(SystemParam.class);

			StringBuilder url = new StringBuilder("https://api.weixin.qq.com/cgi-bin/token");
			url.append("?grant_type=client_credential")
			   .append("&appid=").append(params.getWechatAppid())
			   .append("&secret=").append(params.getWechatSecret());

			String result = HttpUtil.get(url.toString());

			System.err.println(result);

			if(StrUtil.isNotEmpty(result)) {

				JSONObject json = JSONObject.parseObject(result);

				if(json.containsKey("access_token") && json.containsKey("expires_in")) {

					ACCESS_TOKEN = json.getString("access_token");
					EXPIRES_TIME = now.getTime() + json.getLongValue("expires_in");

					return ACCESS_TOKEN;
				}
			}
		}

		return ACCESS_TOKEN;
	}

	public static String code2Session(String code) {

		SystemParam params = ContextUtil.getBean(SystemParam.class);

		StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session");
		url.append("?appid=").append(params.getWechatAppid())
		   .append("&secret=").append(params.getWechatSecret())
		   .append("&js_code=").append(code)
		   .append("&grant_type=authorization_code");

		String result = HttpUtil.get(url.toString());

		System.out.println(result);

		if(StrUtil.isNotEmpty(result)) {

			JSONObject json = JSONObject.parseObject(result);

			if(json.containsKey("openid")) {

				return json.getString("openid");
			}
		}

		return null;
	}


	public static String getPhone(String code) {

		StringBuilder url = new StringBuilder("https://api.weixin.qq.com/wxa/business/getuserphonenumber");
		url.append("?access_token=").append(getToken());

		JSONObject params = new JSONObject();
		params.put("code", code);

		String result = HttpUtil.post(url.toString(), params.toJSONString());

		System.err.println(result);

		if(StrUtil.isNotEmpty(result)) {

			JSONObject json = JSONObject.parseObject(result);
			if(json.containsKey("phone_info")) {

				JSONObject phoneInfo = json.getJSONObject("phone_info");

				if(phoneInfo.containsKey("phoneNumber")) {

					return phoneInfo.getString("phoneNumber");
				}
			}
		}

		return null;
	}
}
